<template>
    <div id="app">
        <!-- 面包屑 -->
        <div class="break" style="margin-bottom:20px;">
            <t-breadcrumb :max-item-width="'150'">
                <t-breadcrumbItem to="/vue-next/components/menu">店铺管理</t-breadcrumbItem>
                <t-breadcrumbItem @click="$router.push('shorelist')">店铺列表</t-breadcrumbItem>
                <t-breadcrumbItem>添加店铺</t-breadcrumbItem>
            </t-breadcrumb>
        </div>

        <!-- 添加商店操作面板 -->

        <t-form ref="formValidatorStatus" :data="storeInfo" :rules="rules" @reset="onReset" @submit="onSubmit"
            @validate="onValidate">

            <div style="width:350px">
                <t-form-item label="店铺名称" name="name">
                    <t-input v-model="storeInfo.name" placeholder="请输入店铺名称"></t-input>
                </t-form-item>

                <t-form-item label="店铺电话" name="phone">
                    <t-input v-model="storeInfo.phone" placeholder="请输入店铺电话"></t-input>
                </t-form-item>

                <t-form-item label="店铺地址" name="address">
                    <t-input v-model="storeInfo.address" placeholder="请输入搜索地址"></t-input>
                    <t-button variant="outline" theme="success" ghost @click="btn">搜索地址</t-button>
                </t-form-item>

                <div style="display:flex;width:200px;">
                    <t-form-item label="当前纬度" name="latitude">
                        <t-input readonly v-model="storeInfo.latitude"></t-input>
                    </t-form-item>

                    <t-form-item label="当前经度" name="longitude">
                        <t-input readonly v-model="storeInfo.longitude"></t-input>
                    </t-form-item>
                </div>
            </div>
            <div id="map">
                <div id="container" ref="container"></div>
                <div id="panel"></div>
            </div>
            <t-space style="margin-top: 10px;">
                <t-button theme="danger" type="submit">提交店铺</t-button>
            </t-space>
        </t-form>
        <t-notification v-if="show" style="position:fixed;top:20px;right:20px;z-index:99999;" placeholder="bottom-left"
            theme="info" title="添加店铺" content="店铺添加成功！" :duration="1000" @duration-end="show = false" />
    </div>
</template>

<script setup>
import { addStoreData } from '@/http/modules/store'
import { onMounted, reactive, ref, toRaw, watch } from "@vue/runtime-core";
import { ShopIcon } from 'tdesign-icons-vue-next';
import { useRouter } from 'vue-router';
import { MessagePlugin } from 'tdesign-vue-next';

const container = ref();
const router = useRouter();

const input = ref('龙岩学院');
const onEnter = (v) => {
    updataMap()
}

const storeInfo = reactive({
    name: "",
    address: "",
    latitude: 0,
    longitude: 0,
    phone: ''
})

const btn = () => {
    if (storeInfo.address == '') {
        ElMessage.error('请输入搜索内容')
        return
    }
    updataMap()
}

// DOM绑定完毕，立即加载高德地图
onMounted(() => {
    updataMap()
})

// 经纬度变量
const lng = ref(0);
const lat = ref(0);
const show = ref()

// 高德地图搜索模块
const updataMap = () => {

    var map = new AMap.Map("container", {
        resizeEnable: true
    });
    AMap.plugin(["AMap.PlaceSearch"], function () {
        var placeSearch = new AMap.PlaceSearch({ //构造地点查询类
            // zoom: 1,//级别
            pageSize: 5, // 单页显示结果条数
            pageIndex: 1, // 页码
            city: "010", // 兴趣点城市
            citylimit: false,  //是否强制限制在设置的城市内搜索
            map: map, // 展现结果的地图实例
            panel: "panel", // 结果列表将在此容器中进行展示。
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search(storeInfo.address)
    });
    map.on('click', function (e) {
        storeInfo.longitude = e.lnglat.getLng()
        storeInfo.latitude = e.lnglat.getLat()
    });
}

// 提交表单验证规则
const longCheck = (val) => {
    if (val == '0' || val == 0) {
        console.log(val, typeof val, val == 0, val == '0');
        return { result: false, message: '请点击地图获取经纬度', type: 'error' };
    }
    return { result: true, message: '', type: 'success' };
};

// 表单规则
const rules = {
    name: [
        { required: true, message: '店铺名称必填', type: 'error' },
        {
            min: 2,
            message: '店铺名称至少需要两个字',
            type: 'error',
            trigger: 'blur',
        },
    ],
    address: [
        { required: true, message: '地址必填', type: 'error' },
    ],
    latitude: [
        { required: true, message: '纬度必填', type: 'error' },
        { validator: longCheck }
    ],
    longitude: [
        { required: true, message: '经度必填', type: 'error' },
        { validator: longCheck }
    ],
    phone: [
        { required: true, message: '手机号必填', type: 'error' },
    ]
};



const onSubmit = async ({ validateResult, firstError, e }) => {
    e.preventDefault();
    if (validateResult === true) {
        const res = await addStoreData(toRaw(storeInfo))
        show.value = true
        setTimeout(() => {
            router.back()
        }, 1000)
    } else {
        console.log('Validate Errors: ', firstError, validateResult);
        MessagePlugin.warning(firstError);
    }
};


// 添加商店
const addShore = async () => {
    const res = await addStoreData(toRaw(storeInfo))
    show.value = true
    setTimeout(() => {
        router.back()
    }, 500)

}
</script>

<style lang="less" scoped>
#map {
    overflow: hidden;
    display: flex;
    margin-top: 20px;
    border-radius: 10px;

    #container {
        position: relative;
        width: 70%;
        height: 300px;
    }

    #panel {
        background-color: rgb(238, 238, 238);
        max-height: 90%;
        overflow-y: auto;
        margin: auto;
        height: 300px;
        width: 30%;
    }
}
</style>